#pragma once

#include "pch.h"
#include <GLFW/glfw3.h>

struct Joystick
{
   
    enum Btn
    {
        A = 0,
        B = 1,
        X = 2,
        Y = 3,
        LB = 4,
        RB = 5,
        BACK = 6,
        START = 7,
        LP = 8,
        RP = 9,
        UP = 10,
        RIGHT = 11,
        DOWN = 12,
        LEFT = 13,
    };
    

    struct Event
    {
        int btn;
        int type;
    };

    int numAxes = 0;
    int numBtns = 0;


    float* axes;
    unsigned char* btns;

    Joystick()
    {
        axes = new float[20];
        btns = new unsigned char[20];
    }
    ~Joystick()
    {
        delete[] axes;
        delete[] btns;
    }
    std::vector<Event> evs;

    bool KeyStates(int k, int t)
    {
        if (btns == 0)
        {
            return false;
        }
        if (numAxes > t)
        {
            return btns[k] == t;
        }
        return false;
    }
    bool KeyPressing(int k)
    {
        return KeyStates(k, GLFW_PRESS);
    }
    bool KeyRelease(int k)
    {
        return KeyStates(k, GLFW_RELEASE);
    }
    void OnJoystick(int joy, int e);
    void OnAxes(const float* a, int count)
    {
        this->axes = new float[count];

  

        memcpy(this->axes, a, sizeof(float) * count);
        this->numAxes = count;



    }
    void OnButton(const unsigned char* btn, int count)
    {
        this->numBtns = count;

        if (this->btns != 0 && btn != 0)
        {
            for (int i = 0; i < count; i++)
            {
                if (this->btns[i] != btn[i])
                {
                    Event e;
                    e.type = btn[i];
                    e.btn = i;
                    this->evs.push_back(e);
                }
            }
        }
    
        this->btns = new unsigned char[count];
        memcpy(this->btns, btn, sizeof(unsigned char) * count);

    }

    void OnClearEvent()
    {
        evs.clear();
    }

    bool KeyEvent(int key, int e)
    {
        for (const auto& s : evs)
        {
            if ((key == s.btn) && (e = s.type))
            {
                return true;
            }
        }
        return false;
    }

    
};
